package edu.shzu.manage.controller;

import edu.shzu.manage.entity.User;
import edu.shzu.manage.service.UserService;
import edu.shzu.manage.util.Result;
import edu.shzu.manage.vo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin //允许前端跨域访问，若带有参数，则访问受限
public class UserController {
    /**@Autowired注解实现依赖注入
     *使构造函数、字段、设值方法或配置方法可以被Spring依赖注入工具自动装配（Autowired）。
     *用于字段：字段在bean构造之后，任何配置方法被调用之前被注入。
     *注入的类需要是一个组件（@Component）。该注解不要求字段是public。
     */
    @Autowired
    UserService userService;

    /**
     * 登录验证密码，返回一个结果
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result checkUser(@RequestBody User user) {
        UserRole userRole = userService.checkUser(user);
        if (userRole != null) {
            System.out.println(userRole);
            return Result.success(userRole);
        } else {
            return Result.fail();
        }
    }

    @GetMapping("/queryByPage")
    public Result query(String str) {
        List<UserRole> userRoles = userService.query(str);
        if (userRoles.size() > 0) {
            return Result.success(userRoles);
        } else {
            return Result.fail();
        }
    }

    /**
     * 模糊查询
     * @param str
     * @return
     */
    @GetMapping("/query")
    public Result queryByPage(String str,Integer pageNum,Integer pageSize) {
        List<UserRole> userRoles = userService.queryByPage(str,pageNum,pageSize);
        if (userRoles.size() > 0) {
            return Result.success(userRoles);
        } else {
            return Result.fail();
        }
    }

    /**
     * 根据ID 查询用户,查询用户部分信息
     * 路径传参需要 @PathVariable注解
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable Integer id) {
        UserRole resultUserRole = userService.getUserById(id);
        if (resultUserRole != null) {
            System.out.println(resultUserRole);
            return Result.success(resultUserRole);
        } else {
            return Result.fail();
        }
    }


    /**
     * 查询所有用户,分页
     * @return
     */
    @GetMapping("/list")
    public Result getAllUser(Integer pageNum,Integer pageSize) {
        List<UserRole> userRoleList = userService.getAllUser(pageNum,pageSize);
        //若集合个数大于0  则说明查询有值
        if (userRoleList.size() > 0 ) {
            System.out.println(userRoleList);
            return Result.success(userRoleList);
        } else {
            return Result.fail();
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/lists")
    public Result getAllUser() {
        List<UserRole> userRoleList = userService.getAllUsers();
        //若集合个数大于0  则说明查询有值
        if (userRoleList.size() > 0 ) {
            System.out.println(userRoleList);
            return Result.success(userRoleList);
        } else {
            return Result.fail();
        }
    }

    /**
     * 添加用户
     * @param userRole
     * @return
     */
    @PostMapping("/insert")
    @Transactional
    public Result addUser(@RequestBody UserRole userRole) {
        User newUser = new User();
        newUser.setUserName(userRole.getUserName());
        newUser.setPassword(userRole.getPassword());
        newUser.setEmail(userRole.getEmail());
        newUser.setCreateTime(userRole.getCreateTime());
        int i = userService.addUser(newUser);  //先插入  插入后会返回新自增的id
        Integer userId = newUser.getUserId();
        Integer roleId = userRole.getRoleId();
        if (i > 0) {
            userService.insertUserRole(userId,roleId);
            return Result.success();
        } else {
            return Result.error(3001,"添加用户失败");
        }
    }

    /**
     * 根据ID 删除用户信息
     * @param id
     * @return
     */
    @DeleteMapping("/{userId}")
    @Transactional
    public Result deleteUser(@PathVariable("userId") Integer id) {
        int i = userService.deleteUser(id);
        if (i > 0) {
            userService.deleteUserRole(id);
            return Result.success();
        } else {
            return Result.error(3002,"删除用户失败");
        }
    }

    /**
     * 修改用户信息
     * @param userRole
     * @return
     */
    @PutMapping("/update")
    @Transactional
    public Result updateUser(@RequestBody UserRole userRole) {
        Integer userId = userRole.getUserId();
        Integer roleId = userRole.getRoleId();
        User user = new User();
        user.setUserId(userId);
        user.setUserName(userRole.getUserName());
        user.setPassword(userRole.getPassword());
        user.setEmail(userRole.getEmail());

        int i = userService.updateUser(user);
        if (i > 0) {
            userService.deleteUserRole(userId);
            userService.insertUserRole(userId,roleId);
            return Result.success();
        } else {
            return Result.error(3003,"更新用户失败");
        }
    }
}
